package com.lovemanai.listener;

import java.sql.ResultSet;
import java.sql.SQLException;

import javax.servlet.ServletRequestEvent;
import javax.servlet.ServletRequestListener;
import javax.servlet.annotation.WebListener;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import com.lovemanai.dao.DbDao;

/**
 * 监视在线用户数
 * @author lovemanai
 *
 */
@WebListener
public class RequestListener implements ServletRequestListener {

	@Override
	public void requestDestroyed(ServletRequestEvent sre) {
		
	}

	@Override
	public void requestInitialized(ServletRequestEvent sre) {
		System.out.println("用户请求被拦截。。。。。");
		
		/*
		 * 每次用户请求到达时，如果请求是新的，获取用户信息插入到数据表中
		 * 如果请求不是新的，则更新用户信息
		 */
		
		//数据库连接参数
		String url = "jdbc:mysql://localhost:3306/crazyit";
		String user = "root";
		String password = "root";
		String driver = "com.mysql.jdbc.Driver";
		
		//获得request对象
		HttpServletRequest request = (HttpServletRequest) sre.getServletRequest();
		//获得session对象
		HttpSession session = request.getSession();
		//获得session ID
		String sessionId = session.getId();
		//获得访问的IP
		String ip = request.getRemoteAddr();
		//获得正在访问的页面
		String page = request.getRequestURL().toString();
		
		String username = (String) session.getAttribute("username");
		
		//未登录作为游客处理
		username = username == null ? "游客" : username;
		
		ResultSet rs = null;
		
		try {
			DbDao dbDao = new DbDao(url, user, password, driver);
			String sql1 = "select * from userinfo where sessionid = ?";
			rs = dbDao.query(sql1, sessionId);
			
			//如果session ID 存在则为旧的会话
			if(rs.next()) {
				//更新信息
				rs.updateString(5, page);
				rs.updateLong(6, System.currentTimeMillis());
				rs.updateRow();
			} else { 
				String sql2 = "insert into userinfo(sessionid, username, ip, page, accesstime) "
						+ "value (?,?,?,?,?)"; 
				//否则为新会话，将新纪录插入到数据库
				dbDao.update(sql2, sessionId, username, ip, page,System.currentTimeMillis());
			} 
		} catch (SQLException e) {
			e.printStackTrace();
		}
			
	}

}
